package com.boco.pciv.controller.company;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.boco.pciv.SysProperties;
import com.boco.pciv.controller.PcivController;
import com.boco.pciv.core.entity.*;
import com.boco.pciv.core.exception.PcivException;
import com.boco.pciv.core.security.LoginUser;
import com.boco.pciv.core.util.UploadFileUtil;
import com.boco.pciv.entity.project.CompanyInfo;
import com.boco.pciv.service.company.ICompanyService;
import com.boco.pciv.service.sys.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wzx on 2020/7/10.
 */
@RestController
@RequestMapping(value="/company/")
public class CompanyController extends PcivController {
    Logger logger = LoggerFactory.getLogger(CompanyController.class);
    @Resource
    private IUserService iUserService;
    @Resource
    private ICompanyService iCompanyService;
    @Autowired
    SysProperties sysConfig;

    @GetMapping("/list")
    public PageResultBase getList(String name, LayUIPager pageParam) {
        SearchCriteria param = new SearchCriteria();
        param.setPager(pageParam);
        param.putCriteria("name", name);
        PageResultBase result = iCompanyService.getPage(param);
        addOperationLog("查询", "企业管理查询");
        return result;
    }

    @GetMapping(value="/dd4Company")
    public BizResponse getdd4Company(Integer hasAll) {
        //下拉框
        List<SelectItem> list = new ArrayList<SelectItem>();
//        if (hasAll != null && hasAll == 1) {
//            list.add(new SelectItem("", "请选择", "Company"));
//        }
        List<CompanyInfo> result = iCompanyService.getAll();
        for (CompanyInfo dd : result) {
            list.add(new SelectItem(dd.getLicNo(), dd.getName(), "Company"));
        }
        return BizResponseUtil.list(list);
    }

    @GetMapping("/info")
    public BizResponse getInfo(String id) {
        LoginUser user=getCurUser();
        if(StrUtil.isBlank(id)){
            id=user.getDeptId();
        }
        CompanyInfo result = iCompanyService.getCompanyInfo(id);
        return BizResponseUtil.single(result);
    }


    @PostMapping("/add")
    public BizResponse addCompany(CompanyInfo companyInfo) {
        if (companyInfo == null) {
            return BizResponseUtil.fail("新增信息不能为空");
        }
        try {
            String str=iCompanyService.reColoms(companyInfo);
            if(StrUtil.isNotBlank(str)) {
                return BizResponseUtil.fail(str);
            }
            String pwd = sysConfig.getCompanyDefaultPassword() + companyInfo.getPhone().substring(7, 11);
            if(sysConfig.getCompanyDefaultPassword().length()!=5){
                pwd = sysConfig.getCompanyDefaultPassword();
            }
            companyInfo.setDefPwd(pwd);
            companyInfo.setCreateUser(getCurUserId());
            companyInfo.setCompanyid(sysConfig.getCompanyRoleID());
            iCompanyService.addUser(companyInfo);

            companyInfo.setCreateUser(getCurUserId());
            companyInfo.setDefPwd(pwd);
            iCompanyService.add(companyInfo);
            addOperationLog("新增", String.format("新增%s:%s",sysConfig.getCompanyName(),companyInfo.getName()));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/edit")
    public BizResponse editCompany(CompanyInfo companyInfo) {
        try {
//            String str=iCompanyService.reColoms(companyInfo);
//            if(StrUtil.isNotBlank(str)) {
//                return BizResponseUtil.fail(str);
//            }
            CompanyInfo result = iCompanyService.getCompanyInfo(String.valueOf(companyInfo.getId()));
            if (!result.getPhone().equals(companyInfo.getPhone())) {
                String pwd = sysConfig.getCompanyDefaultPassword() + companyInfo.getPhone().substring(7, 11);
                if(sysConfig.getCompanyDefaultPassword().length()!=5){
                    pwd = sysConfig.getCompanyDefaultPassword();
                }
                iUserService.deleteByUserId(result.getPhone());
                companyInfo.setDefPwd(pwd);
                companyInfo.setCreateUser(getCurUserId());
                companyInfo.setCompanyid(sysConfig.getCompanyRoleID());
                iCompanyService.addUser(companyInfo);
                companyInfo.setDefPwd(pwd);
            }
            companyInfo.setUpdateTime(DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss"));
            iCompanyService.edit(companyInfo);
            addOperationLog("修改", String.format("更新企业:%s", companyInfo.getId()));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/delete")
    public BizResponse deleteCompany(Integer id, String phone,String status) {
        try {
//            iUserService.deleteByUserId(phone);
            Map<String, Object> map = new HashMap();
            map.put("id",id);
            map.put("userId",phone);
            if("del".equals(status)){
                map.put("status",1);
                map.put("state",3);
            }
            else{
                map.put("status",0);
                map.put("state",1);
            }
            iCompanyService.updateUserStatus(map);
            iCompanyService.deleteCompany(map);
            addOperationLog("删除", String.format("删除%s:%s",sysConfig.getCompanyName(), id));
            return BizResponseUtil.success(MSG_ExeOK);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }


    @PostMapping("/pwdResert")
    public BizResponse pwdResert(String phone) {
        try {
            String newpwd = sysConfig.getCompanyDefaultPassword() + phone.substring(7, 11);
            if(sysConfig.getCompanyDefaultPassword().length()!=5){
                newpwd = sysConfig.getCompanyDefaultPassword();
            }
            iUserService.modifyPassword(phone, newpwd);
            return BizResponseUtil.success(MSG_ExeOK, newpwd);
        } catch (PcivException ex) {
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.error(ex);
        } catch (Exception e) {
            logger.warn(MSG_ExeERROR, e);
            return BizResponseUtil.fail(MSG_ExeERROR + e.getMessage());
        }
    }

    @PostMapping("/upload")
    public BizResponse upload(MultipartFile file, HttpServletRequest request, String type) {
        String filePath = "";
        try {
            String fileDir = request.getSession().getServletContext().getRealPath("\\upload\\");
            String localFileName = UploadFileUtil.uploadFile(file, fileDir);
            filePath = fileDir + "\\" + localFileName;
            ExcelReader reader = ExcelUtil.getReader(filePath);
            List<Map<String, Object>> readAll = reader.readAll();
            reader.close();
            String newpwd = sysConfig.getCompanyDefaultPassword();
            if(sysConfig.getCompanyDefaultPassword().length()!=5){
                newpwd = sysConfig.getCompanyDefaultPassword();
            }
            String result=iCompanyService.upload(readAll,type,getCurUserId(),newpwd);

            FileUtil.del(filePath);//删除临时文件
            if (StrUtil.isBlank(result)) {
                return BizResponseUtil.success(MSG_ExeOK);
            } else {
                return BizResponseUtil.fail(result);
            }
        } catch (Exception ex) {
            if (FileUtil.exist(filePath)) {
                FileUtil.del(filePath);//删除临时文件
            }
            logger.warn(MSG_ExeERROR, ex);
            return BizResponseUtil.fail(MSG_ExeERROR);
        }
    }

}
